import { Context, Schema, h } from 'koishi'

export const name = 'senmo-twitch-broadcast'

export interface Config {
  broadcastPrefix: string
  keywordList: string[]
}

export const Config: Schema<Config> = Schema.intersect([

  Schema.object({
    broadcastPrefix: Schema.string()
      .description('广播前缀')
      .default('[广播]'),
    keywordList: Schema.array(String)
      .description('关键词列表，必须包含全部关键词才能推送。 不分大小写')
      .default(['Twitch', '直播', 'senmo_awa'])
  })

])

export function apply(ctx: Context, config: Config) {

  ctx.on('message', async ( session ) => {

    if ( session.userId !== session.bot.selfId ) return;

    let textStr = '';
    for ( const e of h.parse(session.content) ){
      if ( e.type === 'text' ) {
        textStr += e.attrs.content;
      }
    }

    if ( textStr.startsWith(config.broadcastPrefix) ) return;

    const hit: boolean = config.keywordList.every( s => textStr.includes(s) );
    if ( !hit ) return;

    const guildList = await session.bot.getGuildList();

    for ( const g of guildList.data ){
      ctx.logger.info(`g = ${JSON.stringify(g)}`);
      await session.bot.sendMessage(g.id, `${config.broadcastPrefix} ${session.content}`);
    }

  })

}
